﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using Home.Site.Helpers;
using Home.Site.Models.DataLayer;

namespace Home.Site.Upload
{
    public class DataBuilder : IDataBuilder
    {
        private readonly IPhotoRepository photoRepository;

        public DataBuilder(IPhotoRepository photoRepository)
        {
            this.photoRepository = photoRepository;
        }

        public void BuildPhoto(int albumId, string author, string fileName, string contentType, string physicalFileName)
        {
            var photo = new Photo
                {
                    Author = author,
                    DatePublish = DateTime.Now.Date,
                    FileName = fileName,
                    PhotoAlbumId = albumId,
                    PhysicalName = physicalFileName,
                    TypeData = contentType,
                    Visible = true,
                    Main = false
                };
            photoRepository.InsertOrUpdate(photo);
            photoRepository.Save();
        }

        public void BuildImages(HttpPostedFile file, string pathFull, string pathThumb, string fileNamePath, int fW, int fH, int tW, int tH)
        {
            var fullSize = new Size(fW, fH);
            var thumbSize = new Size(tW, tH);

            Image image = new Bitmap(file.InputStream);

            var fullImage = ImageHelper.ResizeImage(image, fullSize);
            SaveJpeg(pathFull + fileNamePath, (Bitmap)fullImage, 85);

            var thumbImage = ImageHelper.ResizeImage(image, thumbSize);
            SaveJpeg(pathThumb + fileNamePath, (Bitmap)thumbImage, 85);
        }

        public void BuildImage(HttpPostedFile file, string pathFull, string fileNamePath, int fW, int fH)
        {
            var fullSize = new Size(fW, fH);
           
            Image image = new Bitmap(file.InputStream);

            var fullImage = ImageHelper.ResizeImage(image, fullSize);
            SaveJpeg(pathFull + fileNamePath, (Bitmap)fullImage, 85);
        }

        public void SaveJpeg(string path, Bitmap img, long quality)
        {
            var qualityParam = new EncoderParameter(Encoder.Quality, quality);
            
            var jpegCodec = ImageHelper.GetEncoderInfo("image/jpeg");

            if (jpegCodec == null) return;

            var encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = qualityParam;

            img.Save(path, jpegCodec, encoderParams);
        }
    }
}